"""
五子棋游戏GUI界面
使用Pygame实现图形化界面
"""

import pygame
import sys
from config import *


class GameGUI:
    """游戏图形界面类"""
    
    def __init__(self, board):
        """
        初始化GUI
        
        Args:
            board: Board对象
        """
        pygame.init()
        
        self.board = board
        self.screen = pygame.display.set_mode((WINDOW_SIZE, WINDOW_SIZE + STATUS_HEIGHT))
        pygame.display.set_caption('五子棋 - MCTS AI对战')
        
        # 字体
        self.font_large = pygame.font.Font(None, 48)
        self.font_medium = pygame.font.Font(None, 36)
        self.font_small = pygame.font.Font(None, 24)
        
        # 状态
        self.thinking = False
        self.winner = None
        self.game_over = False
    
    def draw(self, current_player=None):
        """
        绘制整个游戏界面
        
        Args:
            current_player: 当前玩家（1或-1）
        """
        self.screen.fill(COLOR_BG)
        
        # 绘制棋盘网格
        self.draw_grid()
        
        # 绘制棋子
        self.draw_pieces()
        
        # 绘制状态信息
        self.draw_status(current_player)
        
        pygame.display.flip()
    
    def draw_grid(self):
        """绘制棋盘网格线"""
        # 绘制横线和竖线
        for i in range(BOARD_SIZE):
            # 横线
            start_pos = (MARGIN, MARGIN + i * CELL_SIZE)
            end_pos = (MARGIN + (BOARD_SIZE - 1) * CELL_SIZE, MARGIN + i * CELL_SIZE)
            pygame.draw.line(self.screen, COLOR_LINE, start_pos, end_pos, 2)
            
            # 竖线
            start_pos = (MARGIN + i * CELL_SIZE, MARGIN)
            end_pos = (MARGIN + i * CELL_SIZE, MARGIN + (BOARD_SIZE - 1) * CELL_SIZE)
            pygame.draw.line(self.screen, COLOR_LINE, start_pos, end_pos, 2)
        
        # 绘制天元和星位（装饰点）
        star_positions = [(3, 3), (3, 11), (11, 3), (11, 11), (7, 7)]
        for row, col in star_positions:
            x = MARGIN + col * CELL_SIZE
            y = MARGIN + row * CELL_SIZE
            pygame.draw.circle(self.screen, COLOR_LINE, (x, y), 5)
    
    def draw_pieces(self):
        """绘制所有棋子"""
        for i in range(BOARD_SIZE):
            for j in range(BOARD_SIZE):
                if self.board.board[i][j] != 0:
                    x = MARGIN + j * CELL_SIZE
                    y = MARGIN + i * CELL_SIZE
                    
                    # 选择颜色
                    color = COLOR_BLACK if self.board.board[i][j] == 1 else COLOR_WHITE
                    
                    # 绘制棋子
                    pygame.draw.circle(self.screen, color, (x, y), CELL_SIZE // 2 - 2)
                    pygame.draw.circle(self.screen, COLOR_LINE, (x, y), CELL_SIZE // 2 - 2, 2)
                    
                    # 标记最后一步（红色小圆点）
                    if self.board.last_move and self.board.last_move == (i, j):
                        pygame.draw.circle(self.screen, COLOR_LAST_MOVE, (x, y), 6)
    
    def draw_status(self, current_player):
        """
        绘制状态栏信息
        
        Args:
            current_player: 当前玩家
        """
        y = WINDOW_SIZE + 20
        
        # 确定显示文本
        if self.game_over:
            if self.winner == 1:
                text = "黑方（人类）获胜！"
                color = COLOR_BLACK
            elif self.winner == -1:
                text = "白方（AI）获胜！"
                color = COLOR_BLACK
            else:
                text = "平局！"
                color = COLOR_BLACK
            
            text_surface = self.font_large.render(text, True, color)
            text_rect = text_surface.get_rect(center=(WINDOW_SIZE // 2, y + 10))
            self.screen.blit(text_surface, text_rect)
            
            # 提示重新开始
            hint_text = "按 R 重新开始 | 按 ESC 退出"
            hint_surface = self.font_small.render(hint_text, True, COLOR_TEXT)
            hint_rect = hint_surface.get_rect(center=(WINDOW_SIZE // 2, y + 50))
            self.screen.blit(hint_surface, hint_rect)
            
        elif self.thinking:
            text = "AI思考中..."
            text_surface = self.font_medium.render(text, True, COLOR_TEXT)
            text_rect = text_surface.get_rect(center=(WINDOW_SIZE // 2, y + 20))
            self.screen.blit(text_surface, text_rect)
            
            # 绘制简单的加载动画
            self.draw_loading_animation(WINDOW_SIZE // 2, y + 50)
            
        else:
            if current_player == PLAYER_HUMAN:
                text = "黑方（人类）回合 - 请落子"
                color = COLOR_BLACK
            else:
                text = "白方（AI）回合"
                color = COLOR_TEXT
            
            text_surface = self.font_medium.render(text, True, color)
            text_rect = text_surface.get_rect(center=(WINDOW_SIZE // 2, y + 20))
            self.screen.blit(text_surface, text_rect)
    
    def draw_loading_animation(self, x, y):
        """
        绘制加载动画（简单的旋转圆点）
        
        Args:
            x: 中心x坐标
            y: 中心y坐标
        """
        import time
        angle = (time.time() * 2) % (2 * 3.14159)
        
        for i in range(8):
            dot_angle = angle + i * 3.14159 / 4
            dot_x = int(x + 30 * pygame.math.Vector2(1, 0).rotate_rad(dot_angle).x)
            dot_y = int(y + 30 * pygame.math.Vector2(1, 0).rotate_rad(dot_angle).y)
            
            alpha = int(255 * (i + 1) / 8)
            color = (alpha, alpha, alpha)
            pygame.draw.circle(self.screen, color, (dot_x, dot_y), 4)
    
    def get_board_position(self, pos):
        """
        将鼠标位置转换为棋盘坐标
        
        Args:
            pos: 鼠标位置 (x, y)
        
        Returns:
            tuple: 棋盘坐标 (row, col)
        """
        x, y = pos
        col = round((x - MARGIN) / CELL_SIZE)
        row = round((y - MARGIN) / CELL_SIZE)
        
        # 确保坐标在有效范围内
        row = max(0, min(BOARD_SIZE - 1, row))
        col = max(0, min(BOARD_SIZE - 1, col))
        
        return row, col
    
    def set_thinking(self, thinking):
        """
        设置AI思考状态
        
        Args:
            thinking: 是否正在思考
        """
        self.thinking = thinking
    
    def set_game_over(self, winner):
        """
        设置游戏结束状态
        
        Args:
            winner: 获胜者（1、-1或0）
        """
        self.game_over = True
        self.winner = winner
    
    def reset(self):
        """重置GUI状态"""
        self.thinking = False
        self.winner = None
        self.game_over = False
    
    def show_message(self, message, duration=2000):
        """
        显示临时消息
        
        Args:
            message: 消息文本
            duration: 显示时长（毫秒）
        """
        text_surface = self.font_medium.render(message, True, (255, 0, 0))
        text_rect = text_surface.get_rect(center=(WINDOW_SIZE // 2, WINDOW_SIZE // 2))
        
        # 绘制半透明背景
        overlay = pygame.Surface((WINDOW_SIZE, WINDOW_SIZE))
        overlay.set_alpha(128)
        overlay.fill((255, 255, 255))
        self.screen.blit(overlay, (0, 0))
        
        # 绘制消息
        self.screen.blit(text_surface, text_rect)
        pygame.display.flip()
        
        pygame.time.wait(duration)
    
    def draw_menu(self, options, selected=0):
        """
        绘制菜单界面
        
        Args:
            options: 选项列表
            selected: 当前选中的选项索引
        """
        self.screen.fill(COLOR_BG)
        
        # 标题
        title = "五子棋 - MCTS AI"
        title_surface = self.font_large.render(title, True, COLOR_TEXT)
        title_rect = title_surface.get_rect(center=(WINDOW_SIZE // 2, 100))
        self.screen.blit(title_surface, title_rect)
        
        # 选项
        for i, option in enumerate(options):
            color = (255, 0, 0) if i == selected else COLOR_TEXT
            text_surface = self.font_medium.render(option, True, color)
            text_rect = text_surface.get_rect(center=(WINDOW_SIZE // 2, 200 + i * 60))
            self.screen.blit(text_surface, text_rect)
        
        pygame.display.flip()
